﻿using System;
using System.Web;
using System.Data.SqlClient;
using Grishko.DataTier;
using AgencyEntityLib.BaseEntity;
using OutdoorLib.Context;
using OutdoorLib.BaseEntity.Agency;
using OutdoorLib.BaseEntity.Constraction;
using OutdoorLib.BaseEntity.Face;
using Grishko.SerilizeTools;
using Grishko.DataTier.SqlSentence;


namespace OutdoorLib.BaseEntity.WS
{
    /// <summary>
    /// Инкапсулирует обработку объектов содержащихся в Agency
    /// Agency|Employeers|SurfaceLists|Discounts
    /// </summary>
    public class wsAgency:EntitySingle 
    {
        public const string wsKey_CurrentAgency = "CurrentAgency";
        public const string wsKey_CurrentEmployeer = "CurrentEmployeer";

        public wsAgency()
        {
            //Uncomment the following line if using designed components 
            //InitializeComponent(); 
        }

        #region STATIC_TOOLS
        /// <summary>
        /// сбросить агентсво из кэша
        /// </summary>
        public static void Reset()
        {
            CacheTools.ResetSessionCache(wsKey_CurrentAgency);
            CacheTools.ResetSessionCache(wsKey_CurrentEmployeer);
        }

        #endregion 

        #region AGENCY_READWRITE
        /// <summary>
        /// Возвращеат агентсво соответсв. текущему пользователю системы.
        /// </summary>
        /// <returns></returns>
        public static AgencyEntity GetAgency()
        {
            //Func<string> F = delegate()
            //{
            //    return "";
            //};

            // пользователь не идентифизирован
            if (!HttpContext.Current.User.Identity.IsAuthenticated) 
                                                                   return null;


           // string ID = wsKey_CurrentAgency;


            /////Запрос вэб службы грузим агентсво и кэшируем не в сессии ?
            //if (HttpContext.Current.Session == null) 
            //{
            //    if (!CacheTools.IsCacheObject(ID))
            //    {
            //        AgencyEntity  a = GetAgency(GetAgencyId());
            //        CacheTools.SetCacheObject(ID, a);
            //        return a;
            //    }
            //    else
            //        return (AgencyEntity)CacheTools.GetCacheObect(ID);
            //}

            // Обычный запрос 
            if (!CacheTools.IsSessionCacheObject(wsKey_CurrentAgency))
            {
                AgencyEntity a = GetAgency(GetAgencyId());
                CacheTools.SetSessionCacheObject(wsKey_CurrentAgency, a);
                return a;
            }

            return (AgencyEntity)CacheTools.GetSessionCacheObect(wsKey_CurrentAgency);

        }

        public  static AgencyEntity  GetAgency(string AgencyId)
        {
            if (string.IsNullOrEmpty(AgencyId))
                return null;

            AgencyEntity r = new AgencyEntity();
            r.ID = AgencyId;
            r.Load();
            return r;

        }

        public static void SaveAgency(AgencyEntity a)
        {
            a.Save();
            Reset();
        }

        public static void SaveAgency()
        {
            AgencyEntity a = GetAgency();
            a.Save();
            Reset();
        }

        /// <summary>
        /// Вернуть ид агентсва - которому соответсвует текущий пользователь 
        /// Если определена функция AgencyLib_GlobalConstants._getAgencyId() - вернуть ее результат 
        /// </summary>
        /// <returns></returns>
        private static string GetAgencyId()
        {
            //if (AgencyLib_GlobalConstants._getAgencyId != null)
            //    return AgencyLib_GlobalConstants._getAgencyId();

            SqlConnection Conn = null;
            try
            {
                SecuretyContext SC = AppContext.GetSC();
                Conn = SC.Connection;
                if (Conn.State == System.Data.ConnectionState.Closed) Conn.Open();
                SqlCommand cmd = new SqlCommand("select dbo.fCurrentAgency ()", Conn);
                cmd.CommandType = System.Data.CommandType.Text;
                object r = cmd.ExecuteScalar();
                return r.ToString();
            }

            catch
            {
                return string.Empty;
            }
            finally
            {
                Conn.Close();
            }

        }
        #endregion

        #region EMPLOYEER_READWRITE
        /// <summary>
        /// Возворащает сотрудника соответсвующего текущему логину системы
        /// </summary>
        /// <returns></returns>
        public Employeer GetCurrentEmployeer()
        {
            if (!HttpContext.Current.User.Identity.IsAuthenticated) return null;

            if (!CacheTools.IsSessionCacheObject(wsKey_CurrentEmployeer))
            {
                AgencyEntity a = GetAgency();

                Employeer Empl = a.GetEmployeerByLogin(HttpContext.Current.User.Identity.Name);

                CacheTools.SetSessionCacheObject(wsKey_CurrentEmployeer, Empl);
            }
            return (Employeer)CacheTools.GetSessionCacheObect(wsKey_CurrentEmployeer);
        }

        public Employeer GetEmployeerByLogin(string Login)
        {
            Employeer Empl = new Employeer();
            Empl.ID = null;
            Empl.Login = Login;
            Empl.Load();
            return Empl;
        }
        
       
      
        #endregion
        
        #region SURFACEGROUP_READWRITE
        //public SurfaceGroup GetSurfaceGroup(string ID)
        //{
        //    //AgencyEntity a = GetAgency();
        //    //if (null != a.SurfaceGroups[ID]) return (SurfaceGroup)a.SurfaceGroups[ID];

        //    //if (!CacheTools.IsCacheObject(ID))
        //    //{
        //    //    SurfaceGroup r = new SurfaceGroup();
        //    //    r.ID = ID;
        //    //    if (r.Name.Equals(string.Empty)) r.Name = "Новая группа";
        //    //    CacheTools.SetCacheObject(ID, r);
        //    //    return r;
        //    //}
        //    //return (SurfaceGroup)CacheTools.GetCacheObect(ID);
        //    return null;
        //}
        
        //public SurfaceGroup SaveSurfaceGroup(SurfaceGroup _SurfaceGroup)
        //{
        //    AgencyEntity a = GetAgency();

        //    if (_SurfaceGroup.ID.IndexOf(AgencyLib_GlobalConstants.qPrefNEW_RECORD) > -1)//режим вставки?
        //    {
        //        string s = _SurfaceGroup.ID;
        //        _SurfaceGroup.ID = _SurfaceGroup.ID.Replace(AgencyLib_GlobalConstants.qPrefNEW_RECORD, "");
        //        CacheTools.ResetCache(s);
        //    }

        //    a.SurfaceGroups.Remove(_SurfaceGroup.ID);
        //    a.SurfaceGroups.Add(_SurfaceGroup);
        //    SaveAgency();
        //    return GetSurfaceGroup(_SurfaceGroup.ID);

        //}

        public SuraceGroupList GetSurfaceGroupList(SuraceGroupList.sqlLoadStatment WhereStatment)
        {
            SuraceGroupList list = new SuraceGroupList();
            list.SqlStatment = WhereStatment;
            list.Load();
            return list;
        }

        public DiscountList GetSurfaceGroupList(DiscountList.sqlLoadStatment WhereStatment)
        {
            DiscountList list = new DiscountList();
            list.SqlStatment = WhereStatment;
            list.Load();
            return list;
        }
        #endregion
                       

        #region DISCOUNT_READWRITE
        public Discount GetDiscount(string ID)
        {
            AgencyEntity a = GetAgency();
            if (null != a.Discounts[ID]) return (Discount)a.Discounts[ID];

            if (!CacheTools.IsCacheObject(ID))
            {
                Discount r = new Discount();
                r.ID = ID;
                if (r.Name.Equals(string.Empty)) r.Name = "Новая скидка";
                r.dtStart = DateTime.Now;
                r.dtFinish = DateTime.Now.AddMonths(1);
                CacheTools.SetCacheObject(ID, r);
                return r;
            }
            return (Discount)CacheTools.GetCacheObect(ID);
        }

        public Discount SaveDiscount(Discount _Discount)
        {
            AgencyEntity a = GetAgency();

            if (_Discount.ID.IndexOf(AgencyLib_GlobalConstants.qPrefNEW_RECORD) > -1)//режим вставки?
            {
                string s = _Discount.ID;
                _Discount.ID = _Discount.ID.Replace(AgencyLib_GlobalConstants.qPrefNEW_RECORD, "");
                CacheTools.ResetCache(s);
            }

            a.Discounts.Remove(_Discount.ID);
            a.Discounts.Add(_Discount);
            SaveAgency();
            return GetDiscount(_Discount.ID);

        }
        #endregion

        #region DEPARTMENT_READWRITE

        public void RemoveDepartment(string DepartmentID)
        {
            AgencyEntity a = GetAgency();
            Department d = (Department)a.Department.Find(DepartmentID);
            d.DestroyMySelf();
        }

        /// <summary>
        /// Вернуть ветку дерева агентсва
        /// </summary>
        /// <param name="FolderId"></param>
        /// <param name="TreeDictionaryID"></param>
        /// <param name="BranchID"></param>
        /// <returns></returns>
        public Department GetDepartment(string DepartmentID)
        {
            try
            {
                AgencyEntity a = GetAgency();
                Department d = (Department)a.Department;
                return (Department)d.Find(DepartmentID);
            }
            catch
            {
                return null;
            }

        }
        #endregion

        #region  EMPLOYEERS_READWRITE
        /// <summary>
        /// Вернуть нового сотрудника и держать ео в кэше пока не прикрепят к какому либо списку
        /// </summary>
        /// <param name="EmplID"></param>
        /// <returns></returns> 
        /// 
        private static Employeer GetNewEmpl(string EmplID)
        {
            if (HttpContext.Current.Cache[EmplID] == null)
            {
                Employeer p = new Employeer();
                p.ID = EmplID;
                HttpContext.Current.Cache.Add(EmplID, p, null, DateTime.MaxValue, TimeSpan.FromMinutes(10), System.Web.Caching.CacheItemPriority.Normal, null);
                return p;
            }

            return (Employeer)HttpContext.Current.Cache[EmplID];

        }
        #endregion

        #region FILTERS_READWRITE
        /// <summary>
        /// сформировать параметр - новый фильтр для спсика фильтров
        /// </summary>
        /// <param name="ListType">тип создаваемого списка</param>
        /// <returns></returns>
        
        

        #endregion



    }
}

